window.onload = function() {
    layui.use(['form', 'upload', 'jquery', 'element','layer'], function() {
        var upload = layui.upload,
            form = layui.form,
            element = layui.element,
            $ = layui.jquery;

        var operation = {
            'el': '',
            'init': function() {
                this.el = new Html({
                    'appendLine': this.appendLine
                });
                this.addAttr();
                this.saveAttrValue();
                this.display();
            },
            tiggleAttrTable: function() {
                var attrNames = $('.attribute-name li');
                if (attrNames.length == 0) {
                    $('.layui-tab').hide();
                } else {
                    $('.layui-tab').show();
                }
            },
            //保存属性名
            'addAttr': function() {
                $('.add-attr').on('click', function() {
                    Utils.layer.open({
                        type: 1,
                        title: false,
                        area: ['285px', '135px'],
                        shade: 0.6, //遮罩透明度
                        closeBtn: 0,
                        shadeClose: true,
                        skin: 'yourclass',
                        content: $('.add-attr-warpper'),
                    });
                    $('.cancel').off('click').on('click', function() {
                        Utils.layer.closeAll();
                    });

                    $('.do').off('click').on('click', function() {
                        var name = $.trim($('[name=attr_name]').val());
                        if (!name) {
                            Utils.layer.msg('请输入规格名称.');
                            return false;
                        }
                        if ($('.size-warpper').find('.label').length >= 2) {
                            Utils.layer.msg('最多只支持2个');
                            return false;
                        }
                        var attr_group = [];
                        $('.size-warpper').find('.label').each(function(i) {
                            var attrName = $('.size-warpper').find('.label').eq(i).text();
                            attr_group.push(attrName)
                        })
                        if (attr_group.indexOf(name) == -1) {
                            $.ajax({
                                'type': 'POST',
                                'url': '/supplier-attribute/add-attribute',
                                'data': {
                                    name: name
                                },
                                'dataType': 'json',
                                'success': function(data) {
                                    Utils.layer.closeAll();
                                    if (data.code != 200) {
                                        Utils.layer.alert(data.msg);
                                        return false;
                                    }

                                    var row = data.data.row;
                                    var list = data.data.list;
                                    $('.size-warpper').prepend([
                                        '<div data-id="', row.id, '" data-class="label label-info" class="layui-btn del-attr">', row.attribute_name, '<i class="cha layui-icon">&#x1007;</i></div>'
                                    ].join(''));

                                    //页面样式渲染
                                    operation.gen(row, list);
                                    $('[name=attr_name]').val('');
                                    $('.displaynone').css({ display: 'list-item' })
                                }
                            });

                            // operation.tiggleAttrTable();
                        } else {
                            Utils.layer.msg('已存在相同属性名')
                        }
                    });
                });
            },
            //删除属性名
            'deleteAttr': function() {
                $('.cha').off('click').on('click', function() {
                    var that = this;
                    Utils.layer.confirm('是否删除？', {
                        btn: ['确定', '取消'] //按钮
                    }, function() {
                        var attr_id = $(that).parent().attr('data-id'),
                            flag = false;
                        $(that).parent().remove();
                        if ($('.tab_' + attr_id).hasClass('layui-this')) {
                            flag = true;
                        }
                        $('.tab_' + attr_id).remove();
                        $('#tab_' + attr_id).remove();
                        if (flag) {
                            var class_name = $('.attribute-name').find('li:last-child').attr('class');
                            $('.attribute-name').find('li:last-child').addClass('layui-this');
                            $('#' + class_name).addClass('layui-show');
                        }
                        Utils.layer.closeAll();
                        operation.tiggleAttrTable();
                    }, function() {
                        Utils.layer.closeAll();
                    });

                })
            },
            //保存属性值
            'saveAttrValue': function() {
                $('.save-attr-value').off('click').on('click', function() {
                    var tr = $(this).parents('tr');
                    var attr_value = tr.find('[name=attr-value]').val();
                    var attr_name = tr.find('[name=attr-name]').val();
                    var id = tr.find('[name=id]').val();
                    if (!attr_value) {
                        Utils.layer.msg('请输入规格值.');
                        return false;
                    }
                    if (!id) {
                        Utils.layer.msg('非法输入.');
                        return false;
                    }
                    if (!attr_name) {
                        Utils.layer.msg('非法输入.');
                        return false;
                    }

                    $.ajax({
                        'type': 'POST',
                        'url': '/supplier-attribute/add-attr-data',
                        'data': {
                            id: id,
                            name: attr_name,
                            value: attr_value
                        },
                        'dataType': 'json',
                        'success': function(data) {
                            Utils.layer.closeAll();
                            if (data.code != 200) {
                                Utils.Utils.layer.alert(data.msg);
                                return false;
                            }
                            //重新渲染整个tr
                            var row = data.data;
                            var index = (tr.prev().length) ? parseInt(tr.prev().find('td').eq(0).text()) + 1 : 1;
                            tr.html([
                                '    <td style="display:none">', index, '</td>',
                                '    <td style="display:none">', row.attr_name, '</td>',
                                '    <td>', row.value, '</td>',
                                '    <td>',
                                '        <span class="layui-btn deltr" style="cursor:pointer;">删除</span>',
                                '    </td>'
                            ].join(''));
                            tr.attr('data-id', row.id);
                            tr.attr('data-attr-name', row.attr_name);
                            tr.attr('data-attr-value', row.value);
                            operation.deleteAttrValue();
                        }
                    });

                });

                // 统一保存.
                // operation.gen();
            },
            //删除属性值
            'deleteAttrValue': function() {
                $('.deltr').off('click').on('click', function() {
                    var tbody = $(this).parents('tbody');
                    $(this).parents('tr').remove();
                    var trs = tbody.find('tr');
                    if (trs.length > 0) {
                        for (var i = 0, len = trs.length; i < len - 1; i++) {
                            $(trs[i]).find('td:first').text(parseInt(i) + 1);
                        }
                    }
                });

            },
            'display': function() {
                $('.display').off('click').on('click', function() {
                    Utils.layer.open({
                        type:1,
                        content:"<div class='layui-form-item'>"+
                                "<div class='layui-inline'><label class='layui-form-label'>原价</label>"+
                                "<input class='layui-input layui-input-inline o-p'/></div>"+
                                "<div class='layui-inline'><label class='layui-form-label'>折扣价</label><input class='layui-input layui-input-inline d-p'/>"+
                                "</div></div>",
                        btn:['确定','跳过'],
                        btn1:function(){
                            var o_p=$(".o-p").val(),
                                d_p=$(".d-p").val();
                            if(o_p!=''&&d_p!=''){
                                operation.el.display(o_p,d_p);
                                Utils.layer.closeAll()
                            }else{
                                Utils.layer.msg("请完善数据")
                            }
                        },
                        btn2:function(){
                            operation.el.display();
                        },
                    })
                });
            },
            'gen': function(row, list) {
                var id = 'tab_' + row.id;
                operation.el.showNav(id, row);
                operation.el.showTab(id, list);
                operation.deleteAttrValue();
                operation.deleteAttr();
                operation.tiggleAttrTable();
                // operation.el.display();
            },
            'appendLine': function() {
                $('.addtr').off('click').on('click', function() {
                    var table = $(this).parents('table').find('tbody');
                    var id = $(this).parents('.layui-tab-item').attr('id');
                    var name = $('.' + id).text();
                    var current_id = id.substring(4);
                    var tr = '<tr>\n' +
                        '<td style="display:none"></td>\n' +
                        '<td style="display:none"><input type="hidden" value="' + current_id + '" name="id"><input type="hidden" value="' + name + '" name="attr-name"> ' + name + ' </td>\n' +
                        '<td><input type="text" value="" class="layui-input" name="attr-value"></td>\n' +
                        '<td>\n' +
                        '<span class="layui-btn deltr" style="cursor:pointer;">删除</span>\n' +
                        '<span class="layui-btn save-attr-value" style="cursor:pointer;">保存</span>\n' +
                        '</td>\n' +
                        '</tr>';
                    // table.append(tr);
                    $(this).parent().parent().before(tr);

                    //保存属性值
                    operation.saveAttrValue();
                    operation.deleteAttrValue();
                });

            }
        };

        function Html(config) {
            if (config.hasOwnProperty('appendLine')) {
                this.appendLine = config.appendLine;
            }
        }

        Html.prototype = {
            constructor: Html,
            // 显示
            // 构建左边的.
            showNav: function(id, row) {
                $('.attribute-name').append([
                    '<li class="' + id + '" data-toggle="tab">' + row.attribute_name + '</li>'
                ].join(''));
                // 先找到自己,添加active.并把兄弟节点删除active
                // $('.' + id).addClass('layui-show').siblings().removeClass('layui-show');
                $('.' + id).addClass('layui-this').siblings().removeClass('layui-this');
                $('.attribute-name').find('li').each(function(i, k) {
                    if ($('.attribute-name').find('li').length == 1) {
                        $('.attribute-name').find('li').eq(0).addClass('layui-this')
                    } else {
                        $('.attribute-name').find('li').eq(i + 1).click(function() {
                            $('.attribute-name').find('li').eq(i + 1).addClass('layui-this').siblings().removeClass('layui-this')
                        })
                    }
                })
            },
            // 构建右边表格.
            showTab: function(id, list) {
                var html = '<div class="layui-tab-item" id="' + id + '">' + this.buildTab(list) + '</div>';
                //显示 属性列表
                $('.attribute-value').append(html);
                $('.attribute-value').find('#' + id).addClass('layui-show').siblings().removeClass('layui-show');
                if (typeof this.appendLine == 'function') {
                    this.appendLine();
                }
            },
            // 添加新行
            appendLine: function() {

            },
            //构建右边的表格
            buildTab: function(list) {
                var trs = [];

                if (list.length > 0) {
                    for (var i = 0, len = list.length; i < len; i++) {
                        trs.push([
                            '<tr data-id="', list[i].id, '" data-attr-name="', list[i].attr_name, '" data-attr-value="', list[i].value, '">',
                            '<td style="display:none">', parseInt(i) + 1, '</td>',
                            '<td style="display:none">', list[i].attr_name, '</td>',
                            '<td>', list[i].value, '</td>',
                            '<td>',
                            '<span class="layui-btn deltr" style="cursor:pointer;">删除</span>',
                            '</td>',
                            '</tr>',
                        ].join(''));
                    }
                }

                return [
                    '<div class="widget">',
                    '     <div class="widget-body" style="padding:0;">',
                    '         <table class="layui-table table">',
                    '             <thead>',
                    '                <tr>',
                    '                    <th style="display:none">编号</th>',
                    '                    <th style="display:none">属性名称</th>',
                    '                    <th>属性值</th>',
                    '                    <th>操作</th>',
                    '                </tr>',
                    '             </thead>',
                    '             <tbody>',
                    trs.join(''),
                    '               <tr><td><span class="layui-btn addtr" style="cursor:pointer;">添加</span></td><td></td></tr>',
                    '             </tbody>',
                    '         </table>',
                    '     </div>',
                    '</div>'
                ].join("");
            },
            // 渲染列表.
            display: function(a,b) {
                // 获取数据.
                var data = this.buildData();
                if (!data.hasOwnProperty("thead")) {
                    Utils.layer.msg('请添加属性和值');
                    return false;
                }

                var thead = data.thead,
                    rows = data.data;
                var th_html = [];
                // console.dir(thead);
                // console.dir(rows);

                for (var i = 0, len = thead.length; i < len; i++) {
                    th_html.push('<th class="width100">' + thead[i] + '</th>');
                }
                th_html.push('<th class="width100">原价</th><th class="width100">折扣价</th><th class="width100">库存</th><th class="width100">图片</th>');
                var trs_html = [];
                for (var i = 0, len = rows.length; i < len; i++) {
                    trs_html.push('<tr>');
                    if (rows[i].attr_name1) {
                        trs_html.push('<td>' + rows[i].attr_name1 + '</td>');
                    }
                    if (rows[i].attr_name2) {
                        trs_html.push('<td>' + rows[i].attr_name2 + '</td>');
                    }
                    if (rows[i].attr_name3) {
                        trs_html.push('<td>' + rows[i].attr_name3 + '</td>');
                    }
                    trs_html.push(
                        '<td><input class="layui-input need" type="number" name="original_price" placeholder="0.00" min="0" value="'+a+'"></td>' +
                        '<td><input class="layui-input need" type="number" name="discount_price" placeholder="0.00" min="0" value="'+b+'"></td>' +
                        '<td><input class="layui-input need" type="number" placeholder="0" name="inventory[]" min="0"></td>' +
                        '<td width="160px;"><input class="pic-card pic-card4" type="file" indexs="' + (i + 1) + '"><input type="hidden" name="attrimgval" value="" class="attrimgvalue need  attrList imgindex' + (i + 1) + '"></td>' +
                        '<td style="display:none;"><input value="' + rows[i].attribute_value_id + '" class="need"/></td></tr>'
                    );

                }
                var html = [
                    '         <table class="layui-table">',
                    '             <thead class="thead">',
                    '                <tr style="background-image: -webkit-linear-gradient(top, #ffffff 0%, #f2f2f2 100%)">',
                    th_html.join(''),
                    '                </tr>',
                    '             </thead>',
                    '             <tbody class="tbody">',
                    trs_html.join(''),
                    '             </tbody>',
                    '         </table>'
                ].join("");
                $('.end-table').html(html);
                // console.dir(data);

            },
            // 生成数据.
            buildData: function() {
                var tbodies = $('.attribute-value').find('tbody');
                var data = [];
                for (var i = 0, len = tbodies.length; i < len; i++) {
                    data.push(this.getAttrs($(tbodies[i])));
                }

                if (data.length == 0 || (!data[0].length && (data[1].length ? !data[1].length : 0) && (data[2].length ? !data[2].length : 0))) {
                    return {};
                }
                var new_data = [],
                    thead = [];
                data = data.filter(function(item) {
                    if (item.length > 0) {
                        return item;
                    }
                });
                for (var i = 0, len = data.length; i < len; i++) {
                    if (data[i].length > 0) {
                        thead.push(data[i][0].attr_name);
                    }
                }

                var first = data.shift();
                first.map(function(item) {
                    if (data.length > 0) {
                        var second = data[0];
                        second.map(function(list) {
                            if (data.length > 1) {
                                var third = data[1];
                                for (var i = 0, len = third.length; i < len; i++) {
                                    new_data.push({
                                        'attribute_value_id': [item.id, list.id, third[i].id].join('-'),
                                        'attr_name1': item.attr_value,
                                        'attr_name2': list.attr_value,
                                        'attr_name3': third[i].attr_value
                                    });
                                }
                            } else {
                                new_data.push({
                                    'attribute_value_id': [item.id, list.id, 0].join('-'),
                                    'attr_name1': item.attr_value,
                                    'attr_name2': list.attr_value,
                                    'attr_name3': ''
                                });
                            }
                        });
                    } else {
                        new_data.push({
                            'attribute_value_id': [item.id, 0, 0].join('-'),
                            'attr_name1': item.attr_value,
                            'attr_name2': '',
                            'attr_name3': ''
                        });
                    }
                });

                return {
                    'thead': thead,
                    'data': new_data
                };
            },

            getAttrs: function(tbody) {
                var trs = tbody.find('tr');
                var data = [];
                for (var i = 0, len = trs.length; i < len - 1; i++) {
                    if (trs[i].getAttribute('data-id') != null && trs[i].getAttribute('data-attr-name') != null && trs[i].getAttribute('data-attr-value') != null) {
                        data.push({
                            'id': trs[i].getAttribute('data-id'),
                            'attr_name': trs[i].getAttribute('data-attr-name'),
                            'attr_value': trs[i].getAttribute('data-attr-value')
                        });
                    }
                    // else{
                    //     Utils.Utils.layer.msg('尚有属性值未保存!');
                    // }

                }
                return data;
            }
        };

        $(function() {
            operation.init();
        });




        var uploader = {
            'data': {
                'token': '',
                'uploadDomain': '',
                'domain': ''
            },
            // 'complete':function(res){
            //     var url="http://"+uploader.data.domain +"/"+ res.key;
            //     $(".pic3").attr("src",url);
            //     $(".pic3-val").val(res.key);
            // },
            'error': function() {
                console.dir(arguments);
            },
            // 分片上传时的进度展示功能在此书写.
            'next': function(response) {
                // var chunks = response.chunks || [];
                // var total = response.total;
            },
            'init': function() {
                $.ajax({
                    'url': '/upload/get-token',
                    'type': 'POST',
                    'dataType': 'json',
                    'success': function(data) {
                        if (data.code != 200) {
                            Utils.Utils.layer.alert(data.msg);
                            return false;
                        }
                        uploader.data.token = data.data.token; // token
                        uploader.data.domain = data.data.domain; // 显示域名
                        // uploader.data.uploadDomain = 'idv093d.qiniudns.com';    // 上传域名
                        // console.log(uploader.data.token)
                    }
                });
            },
            'eventBind': function() {
                this.init();
                $('.pic-card3').on('change', function(e) {
                    var fileList = e.target.files[0];
                    UpladFile(fileList, '.pic3', '.hidden-pic3')
                });
                $('.default').on('change', function(e) {
                    var fileList = e.target.files[0];
                    UpladFile(fileList, '.pic-pic', '')
                });
                $('body').on("change", ".pic-card4", function(e) {
                    var fileList = e.target.files[0];
                    var idx = $(this).attr("indexs");
                    UpladFile(fileList, '', '', idx)
                })

                function UpladFile(ele, showPic, hiddenPic, index) {
                    var fileObj = ele; // js 获取文件对象
                    var formData = new FormData(); // FormData 对象
                    if (fileObj.size / 1024 > 200) { //大于200k，进行压缩上传
                        photoCompress(fileObj, { quality: 0.9 }, function(base64Codes) {
                            //console.log("压缩后：" + base.length / 1024 + " " + base);
                            var bl = convertBase64UrlToBlob(base64Codes);
                            formData.append("file", bl, "file_" + Date.parse(new Date()) + ".jpg"); // 文件对象
                            var token = uploader.data.token;
                            var config = {
                                useCdnDomain: true,
                                disableStatisticsReport: false,
                                region: qiniu.region.z0
                            };
                            var putExtra = {
                                fname: "",
                                params: {},
                                mimeType: ["image/png", "image/jpeg", "image/gif"], // 限制文件类型.
                            };
                            // var file = this.files[0];
                            bl.name = fileObj.name;
                            var file = bl;
                            if (TestFileSuffix(file.name) < 0) {
                                Utils.Utils.layer.msg('请上传 jpg/png 类型图片');
                                return;
                            }
                            var observable;
                            if (file) {
                                // var files=$(this)[0].files[0];    // 用来显示的文件名.需要修改,重名时覆盖
                                var files = file;
                                var key1 = file.name;
                                var key = key1.split(".")[0] + Date.parse(new Date()) + "." + key1.split(".")[1];
                                putExtra.params["x:name"] = key.split(".")[0];
                                // 配置完成的数组.
                                if (showPic == '.pic-pic') {
                                    var subObject = {
                                        next: uploader.next,
                                        error: uploader.error,
                                        complete: function(res) {
                                            var url = "http://" + uploader.data.domain + "/" + res.key;
                                            var newImg = "<div style='display:inline-block;'><div class='detail-img' style='width:150px;height:150px;position:relative;margin:0 10px;'>"
                                            newImg += "<img src='" + url + "' style='width:100%;height:100%;'>"
                                            newImg += "<input type='hidden' name='img_url' class='hidden-picc' value='" + res.key + "'>"
                                            newImg += "<div class='xxx' style='position:absolute;top:0;right:0;width:20px;height:20px;line-height:20px;text-align:center;background:#ddd;cursor:pointer;'>X</div>"
                                            newImg += "</div></div>";
                                            $(".imgs").append(newImg);
                                            delbanner()
                                        }
                                    };
                                } else if (showPic == '.pic3') {
                                    var subObject = {
                                        next: uploader.next,
                                        error: uploader.error,
                                        complete: function(res) {
                                            var url = "http://" + uploader.data.domain + "/" + res.key;
                                            $(showPic).attr("src", url).css('display', 'block');
                                            $(hiddenPic).val(res.key);
                                        }
                                    };
                                } else {
                                    var subObject = {
                                        next: uploader.next,
                                        error: uploader.error,
                                        complete: function(res) {
                                            var showpic = '.imgindex' + index;
                                            $(showpic).val(res.key);
                                        }
                                    };
                                }

                                var subscription;
                                // 调用sdk上传接口获得相应的observable，控制上传和暂停
                                observable = qiniu.upload(files, key, token, putExtra, config);
                                subscription = observable.subscribe(subObject);
                                // subscription.unsubscribe();  // 取消上传.
                            }
                        });
                    } else {
                        var token = uploader.data.token;
                        var config = {
                            useCdnDomain: true,
                            disableStatisticsReport: false,
                            region: qiniu.region.z0
                        };
                        var putExtra = {
                            fname: "",
                            params: {},
                            mimeType: ["image/png", "image/jpeg", "image/gif"], // 限制文件类型.
                        };
                        var file = fileObj
                        // bl.name=fileObj.name;
                        // var file=bl;
                        if (TestFileSuffix(file.name) < 0) {
                            Utils.Utils.layer.msg('请上传 jpg/png 类型图片');
                            return;
                        }
                        var observable;
                        if (file) {
                            // var files=$(this)[0].files[0];    // 用来显示的文件名.需要修改,重名时覆盖
                            var files = file;
                            var key1 = file.name;
                            var key = key1.split(".")[0] + Date.parse(new Date()) + "." + key1.split(".")[1];
                            putExtra.params["x:name"] = key.split(".")[0];
                            // 配置完成的数组.
                            if (showPic == '.pic-pic') {
                                var subObject = {
                                    next: uploader.next,
                                    error: uploader.error,
                                    complete: function(res) {
                                        var url = "http://" + uploader.data.domain + "/" + res.key;
                                        var newImg = "<div style='display:inline-block;'><div class='detail-img' style='width:150px;height:150px;position:relative; margin-right:10px;'>"
                                        newImg += "<img src='" + url + "' style='width:100%;height:100%;'>"
                                        newImg += "<input type='hidden' name='img_url' class='hidden-picc' value='" + res.key + "'>"
                                        newImg += "<div class='xxx' style='position:absolute;top:0;right:0;width:20px;height:20px;line-height:20px;text-align:center;background:#ddd;cursor:pointer;'>X</div>"
                                        newImg += "</div></div>";
                                        $(".imgs").append(newImg);
                                        delbanner()
                                    }
                                };
                            } else if (showPic == '.pic3') {
                                var subObject = {
                                    next: uploader.next,
                                    error: uploader.error,
                                    complete: function(res) {
                                        var url = "http://" + uploader.data.domain + "/" + res.key;
                                        $(showPic).attr("src", url).css('display', 'block');
                                        $(hiddenPic).val(res.key);
                                    }
                                };
                            } else {
                                var subObject = {
                                    next: uploader.next,
                                    error: uploader.error,
                                    complete: function(res) {
                                        var showpic = '.imgindex' + index;
                                        $(showpic).val(res.key);
                                    }
                                };
                            }

                            var subscription;
                            // 调用sdk上传接口获得相应的observable，控制上传和暂停
                            observable = qiniu.upload(files, key, token, putExtra, config);
                            subscription = observable.subscribe(subObject);
                            // subscription.unsubscribe();  // 取消上传.
                        }
                    }
                }

                function photoCompress(file, w, objDiv) {
                    var ready = new FileReader();
                    /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
                    ready.readAsDataURL(file);
                    ready.onload = function() {
                        var re = this.result;
                        canvasDataURL(re, w, objDiv)
                    }
                }

                function canvasDataURL(path, obj, callback) {
                    var img = new Image();
                    img.src = path;
                    img.onload = function() {
                        var that = this;
                        // 默认按比例压缩
                        var w = that.width,
                            h = that.height,
                            scale = w / h;
                        w = obj.width / 1.2 || w / 1.2;
                        h = obj.height / 1.2 || (w / scale) / 1.2;
                        var quality = 0.8; // 默认图片质量为0.7
                        //生成canvas
                        var canvas = document.createElement('canvas');
                        var ctx = canvas.getContext('2d');
                        // 创建属性节点
                        var anw = document.createAttribute("width");
                        anw.nodeValue = w;
                        var anh = document.createAttribute("height");
                        anh.nodeValue = h;
                        canvas.setAttributeNode(anw);
                        canvas.setAttributeNode(anh);
                        ctx.drawImage(that, 0, 0, w, h);
                        // 图像质量
                        if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
                            quality = obj.quality;
                        }
                        // quality值越小，所绘制出的图像越模糊
                        var base64 = canvas.toDataURL('image/jpeg', quality);
                        // 回调函数返回base64的值
                        callback(base64);
                    }
                }
                /**  
                 * 将以base64的图片url数据转换为Blob  
                 * @param urlData  
                 *            用url方式表示的base64图片数据  
                 */
                function convertBase64UrlToBlob(urlData) {
                    var arr = urlData.split(','),
                        mime = arr[0].match(/:(.*?);/)[1],
                        bstr = atob(arr[1]),
                        n = bstr.length,
                        u8arr = new Uint8Array(n);
                    while (n--) {
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    return new Blob([u8arr], { type: mime });
                }

            }
        };

        $('#introduction').on('keyup', function() {
            var indexs = 220;
            var texts = $(this).val().length;
            indexs = indexs - texts;
            if (indexs < 0) {
                Utils.Utils.layer.alert('已超过220个字符');
            }
            $('.introduction_count').html(texts);
        })

        $('.menu-name').on('keyup', function() {
            var num = $(this).val().length;
            if (num > 45) {
                Utils.Utils.layer.msg("字数不能超过45字")
            }
            $('.menu_name_count').text(num)
        })



        function delbanner($this) {
            $('.xxx').unbind('click').on('click', function() {
                if (confirm('确定删除当前图片？')) {
                    $(this).parent().parent().remove();
                }
            })
        }

        //三级联动
        form.on('select(one)',function(data){
            var id=data.value;
            $('.twoclass').html('');
            $('.threeclass').html('<option value="0">请选择三级分类</option>');
            if(id!=0){
                changeclassAjax('.twoclass', id, '二')
            }else{
                form.render('select')
            }
        })
        form.on('select(two)',function(data){
            var id=data.value;
            $('.threeclass').html('');
            if(id!=0){
                changeclassAjax('.threeclass', id, '三')
            }else{
                form.render('select');
            }
        })

        function changeclassAjax(calsss, id, num) {
            $.ajax({
                'url': '/goods/get-tree',
                'type': 'POST',
                'dataType': 'json',
                'data': { id: id },
                'success': function(data) {
                    if (data.code != 200) {
                        Utils.Utils.layer.alert(data.msg);
                        return false;
                    } else {
                        var option = '<option value="0">请选择' + num + '级分类</option>';
                        $.each(data.data, function(indexe, value) {
                            option += '<option value="' + value.id + '">' + value.tree_name + '</option>'
                        });
                        $(calsss).append(option);
                        form.render('select');
                    }
                }
            });
        }

        function DataLength(fData) {
            var intLength = 0
            for (var i = 0; i < fData.length; i++) {
                if ((fData.charCodeAt(i) < 0) || (fData.charCodeAt(i) > 255))
                    intLength = intLength + 2
                else
                    intLength = intLength + 1
            }
            return intLength
        }


        $(document).ready(function() {

            uploader.eventBind();

            //传递数据
            $(".btn-last-googs").on("click", function() {

                var tby = [],is_return=false;
                $(".tbody").find('tr').each(function(i) {
                    var td_val = [];
                    var o_price = $(".tbody").find('tr').eq(i).find(":input[name='original_price']").val();
                    var d_price = $(".tbody").find('tr').eq(i).find(":input[name='discount_price']").val();
                    if(o_price!=''&&d_price==''){
                        Utils.layer.msg("折扣价必填");
                        is_return=true;
                        return false;
                    }
                    $(".tbody").find('tr').eq(i).find('.need').each(function(j) {
                        var needVal = $(".tbody").find('tr').eq(i).find('.need').eq(j).val();
                        
                        if (needVal) {
                            td_val.push(needVal);
                        } else {
                            td_val.push(0);
                        }
                    })
                    tby.push(td_val)
                })
                if(is_return){
                    return false;
                }

                var threeid = $(".threeclass option:selected").val(); //三级分类
                var twoid = $(".twoclass option:selected").val(); //二级分类
                var oneid = $(".oneclass option:selected").val(); //一级分类
                var type = $(":input[name='goods_type']:checked").val();
                var goods_name = $(":input[name='goods_name']").val();
                var key = $(":input[name='key']").val();
                var list_img = $(":input[name='list_img']").val();
                var attr_name = $(":input[name='attr_name']").val();
                var introduction = $("#introduction").val();
                // var content = UE.getEditor('editor').getContent();
                var freight = $(":input[name='freight']").val();
                freight = freight > 0 ? freight : 0;
                var banner = new Array();

                var charNum = $(".menu-name").val().length;
                var attr_describe = [];

                $('.hidden-picc').each(function($i) {
                    banner[$i] = $(this).val();
                });
                
                flag = true;
                if (goods_name == "") {
                    Utils.layer.msg("请输入商品名称");
                    flag = false;
                } else if (charNum > 45) {
                    Utils.layer.msg("商品名称不能超过45字");
                    flag = false;
                } else if (list_img == '') {
                    Utils.layer.msg("请上传封面图");
                    flag = false;
                } else if (banner.length == 0) {
                    Utils.layer.msg("请添加详情图");
                    flag = false;
                } else if (threeid == 0) {
                    Utils.layer.msg("请选择商品三级分类");
                    flag = false;
                }
                $('.attr_describe div').each(function(idx){
                  var key = $(this).find('input[name="key"]').val();
                  var val = $(this).find('input[name="val"]').val();
                  if(key == "" && val == ""){
                    return;
                  }else if(key == "" || val == ""){
                    Utils.layer.msg("请完善属性描述");
                    flag = false;
                    return;
                  }else{
                    attr_describe.push({
                      key: key,
                      val: val
                    })
                  }
                })
                data = {
                    'goods_name': goods_name,
                    'goods_type': type,
                    'key': key,
                    'list_img': list_img,
                    'introduction': introduction,
                    'attr_name': attr_name,
                    'banner': banner,
                    'two_tree_id': twoid,
                    'one_tree_id': oneid,
                    'three_tree_id': threeid,
                    'freight': freight,
                    'tby': tby,
                    'attr_describe':attr_describe
                };
                if (flag) {
                    $.ajax({
                        'url': '/supplier/add',
                        'type': 'POST',
                        'dataType': 'json',
                        'data': data,
                        'success': function(data) {
                            if (data.code != 200) {
                                Utils.layer.msg(data.msg);
                                return false;
                            } else {
                                Utils.layer.msg(data.msg);
                                setTimeout(function() {
                                    location.href = "/supplier/index";
                                }, 1000);
                            }

                        }
                    });
                }
            });
        })

      // 属性描述
      var addAttrDescribe = $('.add_attr_describe');
      var attrDescribe = $('.attr_describe');
      addAttrDescribe.click(function(){
        var inputs = attrDescribe.find('div').last().find('input');
        if(inputs.eq(0).val() == "" && inputs.eq(1).val() == ""){
          return
        }else{
          var htmlStr = '<div><span><input type="text" name="key" class="layui-input" placeholder="属性" /><input type="text" name="val" class="layui-input" placeholder="描述" /></span><b class="layui-btn del_attr_describe">删除</b></div>';
          $(htmlStr).appendTo(attrDescribe)
          delAttrDescribe()
          showAttrDescribe()
        }
      })
      delAttrDescribe()

      function delAttrDescribe(){
        $('.del_attr_describe').unbind('click').click(function(){
          var that = $(this);
          Utils.layer.confirm('确定要删除当前属性描述?', {
            btn: ['确认', '取消'],
            btn1: function(index, layero){
              that.parent('div').remove();
              showAttrDescribe()
              Utils.layer.closeAll()
            }
          })
        })
      }
      function showAttrDescribe(){
        if(attrDescribe.find('div').length == 0){
          attrDescribe.hide()
        }else{
          attrDescribe.show()
        }
      }
    })
}